import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 点赞列表页面视图模型
class LikeListNavigatorViewModel extends BaseViewModel {
  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 获取用户点赞的动态列表
  List<ContentModel> get likedDynamics {
    if (!isLoggedIn || currentUser == null) return [];
    return appState.contentBroadcaster.fetchUserLikedDynamics(currentUser!.id);
  }

  /// 获取用户信息
  UserModel? getUserById(String userId) {
    return appState.userStore.getUserById(userId);
  }

  /// 检查用户是否已点赞
  bool hasUserLiked(String dynamicId) {
    if (!isLoggedIn) return false;
    return appState.contentBroadcaster.hasUserAppreciated(
      dynamicId,
      currentUser!.id,
    );
  }

  /// 切换点赞状态
  Future<bool> toggleLike(String dynamicId) async {
    if (!isLoggedIn) return false;
    return await appState.contentBroadcaster.toggleAppreciation(
      dynamicId: dynamicId,
      userId: currentUser!.id,
    );
  }
}

/// 点赞列表页面
class LikeListStory extends StatefulWidget {
  const LikeListStory({super.key});

  @override
  State<LikeListStory> createState() => _LikeListStoryState();
}

class _LikeListStoryState extends State<LikeListStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LikeListNavigatorViewModel>.reactive(
      viewModelBuilder: () => LikeListNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        viewModel.notifyListeners();
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 标题栏
                  _buildTitleBar(),

                  // 内容区域
                  Expanded(
                    child:
                        viewModel.isLoggedIn
                            ? _buildLikedDynamicsList(viewModel)
                            : _buildLoginPrompt(),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildTitleBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 20.w,
              height: 20.w,
              color: MagmaColor.white,
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text('Liked Posts').blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          SizedBox(width: 32.w),
        ],
      ),
    );
  }

  /// 构建点赞动态列表
  Widget _buildLikedDynamicsList(LikeListNavigatorViewModel viewModel) {
    final likedDynamics = viewModel.likedDynamics;

    if (likedDynamics.isEmpty) {
      return Center(
        child: Text(
          'No liked posts yet',
        ).inter(fontSize: 16.sp, color: MagmaColor.white.withOpacity(0.6)),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 12.w,
          mainAxisSpacing: 12.h,
          childAspectRatio: 182 / 272,
        ),
        itemCount: likedDynamics.length,
        itemBuilder: (context, index) {
          final dynamic = likedDynamics[index];
          return _buildDynamicCard(dynamic, viewModel, index);
        },
      ),
    );
  }

  /// 构建动态卡片
  Widget _buildDynamicCard(
    ContentModel dynamic,
    LikeListNavigatorViewModel viewModel,
    int index,
  ) {
    final isLeftColumn = index % 2 == 0;
    final backgroundImage =
        isLeftColumn
            ? MagmaConstant.dynamicCardLeft
            : MagmaConstant.dynamicCardRight;

    return MagmaTap(
      onTap: () {
        QR.to(
          MagmaRouter.dynamicDetailPath.replaceAll(':dynamicId', dynamic.id),
        );
      },
      child: AspectRatio(
        aspectRatio: 182 / 272,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(backgroundImage),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(2.r),
              ),
              child: Padding(
                padding: EdgeInsets.all(6.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 动态图片
                    Expanded(
                      flex: 6,
                      child: Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage(
                                  dynamic.imagePath ??
                                      dynamic.coverImagePath ??
                                      MagmaConstant.dynamic1,
                                ),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          // 播放图标（仅视频类型显示）
                          if (dynamic.type == ContentType.video)
                            Center(
                              child: Icon(
                                Icons.play_arrow,
                                color: Colors.white,
                                size: 36.w,
                              ),
                            ),
                          // 白色三角形（仅在左列显示）
                          if (isLeftColumn)
                            Positioned(
                              top: 0,
                              left: 0,
                              child: Image.asset(
                                MagmaConstant.triangle,
                                width: 18.w,
                                height: 18.w,
                                color: Colors.white,
                              ),
                            ),
                        ],
                      ),
                    ),

                    SizedBox(height: 12.h),

                    // 动态标题
                    Expanded(
                      flex: 2,
                      child: Text(
                        dynamic.title,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ).blackHanSans(
                        fontSize: 12.sp,
                        color: MagmaColor.black,
                        fontWeight: FontWeight.w400,
                      ),
                    ),

                    // 创建者和点赞
                    Expanded(
                      flex: 1,
                      child: StatefulBuilder(
                        builder: (context, setState) {
                          final isLiked = viewModel.hasUserLiked(dynamic.id);

                          return Row(
                            children: [
                              CircleAvatar(
                                radius: 14.r,
                                backgroundImage: AssetImage(
                                  viewModel
                                          .getUserById(dynamic.userId)
                                          ?.avatar ??
                                      MagmaConstant.avatar1,
                                ),
                              ),
                              SizedBox(width: 6.w),
                              Expanded(
                                child: Text(
                                  viewModel
                                          .getUserById(dynamic.userId)
                                          ?.username ??
                                      'Unknown',
                                ).inter(
                                  fontSize: 12.sp,
                                  color: MagmaColor.black,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              MagmaTap(
                                onTap: () async {
                                  if (!viewModel.isLoggedIn) {
                                    await LoginRequiredDialog.show(context);
                                    return;
                                  }

                                  final wasLiked = isLiked;

                                  final result = await viewModel.toggleLike(
                                    dynamic.id,
                                  );

                                  if (result) {
                                    setState(() {});

                                    if (context.mounted) {
                                      MagmaToast.success(
                                        context,
                                        title: wasLiked ? 'Unliked' : 'Liked',
                                      );
                                    }
                                  } else {
                                    if (context.mounted) {
                                      MagmaToast.error(
                                        context,
                                        title: 'Operation failed',
                                      );
                                    }
                                  }
                                },
                                child: Image.asset(
                                  MagmaConstant.like,
                                  width: 20.w,
                                  height: 20.w,
                                  color:
                                      isLiked ? Colors.red : MagmaColor.black,
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (isLeftColumn)
              Positioned(
                top: -6.w,
                left: -6.w,
                child: Image.asset(
                  MagmaConstant.triangle,
                  width: 30.w,
                  height: 30.w,
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoginPrompt() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(MagmaConstant.logo, width: 120.w, height: 120.w),
          ),

          SizedBox(height: 32.h),

          Text(
            'Please login to view your liked posts',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w600,
          ),

          SizedBox(height: 16.h),

          Text(
            'Discover and save your favorite content',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 14.sp,
            color: MagmaColor.white.withOpacity(0.7),
            fontWeight: FontWeight.w400,
          ),

          SizedBox(height: 40.h),

          MagmaTap(
            onTap: () => QR.to(MagmaRouter.loginPath),
            child: Container(
              width: 200.w,
              height: 56.h,
              decoration: BoxDecoration(
                color: MagmaColor.purple,
                borderRadius: BorderRadius.circular(28.r),
              ),
              child: Center(
                child: Text('Login').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.black,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
